package com.m1.tzolkin.ia;

import com.m1.tzolkin.model.board.ITZBoard;
import com.m1.tzolkin.model.exceptions.EndOfGameException;
import com.m1.tzolkin.model.exceptions.IllegalWorkerOperationException;
import com.m1.tzolkin.model.exceptions.NoMovedWorkersException;
import com.m1.tzolkin.model.exceptions.NoPlaceException;
import com.m1.tzolkin.model.exceptions.NoWorkerHereException;
import com.m1.tzolkin.model.exceptions.NotEnoughCornException;
import com.m1.tzolkin.model.exceptions.NotEnoughWorkersException;
import com.m1.tzolkin.model.exceptions.WaitingOperationsException;
import com.m1.tzolkin.model.players.ITZPlayer;
import com.m1.tzolkin.model.wheels.IWheel;
import com.m1.tzolkin.model.wheels.WheelEnum;

public class StupidIA implements IA {
	
	private final ITZBoard b;
	
	public StupidIA(ITZBoard b) {
		this.b = b;
	}

	@Override
	public void play() {
		ITZPlayer me = b.getCurrentPlayer();
		// Poser ou retirer ?
		boolean poser;
		if (me.getHandPawns().size() == me.getTotalPawns().size()) {
			poser = true;
		} else if (me.getHandPawns().size() == 0) {
			poser = false;
		} else {
			poser = (int) (Math.random() * 2) == 0;
		}
		if (poser) {
			int times = (int) (Math.random() * (me.getHandPawns().size() - 1)) + 1;
			for (int i = 0; i < times; ++i) {
				poser();
			}
		} else {
			int times = (int) (Math.random() * (me.getTotalPawns().size() - me.getHandPawns().size() - 1)) + 1;
			for (int i = 0; i < times; ++i) {
				retirer();
			}
		}
		try {
			b.endTurn();
		} catch (WaitingOperationsException e) {
			// Rien
		} catch (EndOfGameException e) {
			// Rien
		} catch (NoMovedWorkersException e) {
			e.printStackTrace();
		}
	}
	
	private void poser() {
		int wheelnb = (int) (Math.random() * WheelEnum.values().length);
		try {
			b.placeWorker(WheelEnum.values()[wheelnb]);
		} catch (NoPlaceException e) {
			poser();
		} catch (NotEnoughCornException e) {
			poser();
		} catch (IllegalWorkerOperationException e) {
			e.printStackTrace();
		} catch (NotEnoughWorkersException e) {
			e.printStackTrace();
		}
	}
	
	private void retirer() {
		int wheelnb = (int) (Math.random() * WheelEnum.values().length);
		IWheel w = b.getWheel(WheelEnum.values()[wheelnb]);
		int place = 0;
		try {
			place = (int) (Math.random() * (w.getCircuitLength() - w.getMinimalPosition() - 1)) + 1;
		} catch (NoPlaceException e) {
			place = (int) (Math.random() * (w.getCircuitLength() - 1)) + 1;
		}
		if (w.getWorker(place).getOwner() == b.getCurrentPlayer()) {
			try {
				b.takeWorker(WheelEnum.values()[wheelnb], place);
			} catch (IllegalWorkerOperationException e) {
				e.printStackTrace();
			} catch (NoWorkerHereException e) {
				e.printStackTrace();
			}
		} else {
			retirer();
		}
	}
	
}
